/**
 * 本地数据管理器
 * 提供比赛、报名、比赛数据的本地存储管理功能
 * 使用文件系统存储，类似用户数据的存储方式
 */

class LocalDataManager {
  constructor() {
    this.racesKey = 'badminton_races';
    this.signupsKey = 'badminton_signups';
    this.matchesKey = 'badminton_matches';
    this.fs = wx.getFileSystemManager();
  }

  // 生成唯一ID
  generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }

  // 读取JSON文件
  readJsonFile(filePath) {
    try {
      const data = this.fs.readFileSync(filePath, 'utf8');
      if (data && data.trim() !== '') {
        return JSON.parse(data);
      }
      return null;
    } catch (error) {
      // 文件不存在是正常情况，不需要打印错误
      if (error.message && error.message.indexOf('not found') !== -1) {
        console.log('文件不存在，将创建新文件:', filePath);
        return null;
      }
      console.log('读取文件失败:', filePath, error);
      return null;
    }
  }

  // 写入JSON文件
  writeJsonFile(filePath, data) {
    try {
      const jsonString = JSON.stringify(data, null, 2);
      this.fs.writeFileSync(filePath, jsonString, 'utf8');
      return true;
    } catch (error) {
      console.error('写入文件失败:', filePath, error);
      return false;
    }
  }

  // 获取文件路径
  getFilePath(key) {
    try {
      // 直接使用微信小程序的标准用户数据路径
      const userDataPath = wx.env.USER_DATA_PATH;
      
      if (!userDataPath) {
        console.error('USER_DATA_PATH 未定义');
        return null;
      }
      
      const filePath = `${userDataPath}/${key}.json`;
      return filePath;
    } catch (error) {
      console.error('获取文件路径失败:', error);
      return null;
    }
  }

  // ==================== 比赛数据管理 ====================
  
  // 获取所有比赛
  getAllRaces() {
    try {
      const filePath = this.getFilePath(this.racesKey);
      if (!filePath) {
        console.error('无法获取文件路径');
        return [];
      }
      const races = this.readJsonFile(filePath);
      return races || [];
    } catch (error) {
      console.error('获取比赛列表失败:', error);
      return [];
    }
  }

  // 获取单个比赛
  getRace(raceId) {
    try {
      const races = this.getAllRaces();
      // 同时支持 id 和 _id 字段
      return races.find(race => race._id === raceId || race.id === raceId);
    } catch (error) {
      console.error('获取比赛信息失败:', error);
      return null;
    }
  }

  // 保存比赛
  saveRace(raceData) {
    try {
      const races = this.getAllRaces();
      // 同时支持 id 和 _id 字段
      const existingIndex = races.findIndex(race => 
        race._id === raceData._id || race._id === raceData.id || 
        race.id === raceData._id || race.id === raceData.id
      );
      
      if (existingIndex >= 0) {
        // 更新现有比赛
        const existingRace = races[existingIndex];
        const updatedRace = {};
        // 复制现有比赛的所有属性
        for (let key in existingRace) {
          if (existingRace.hasOwnProperty(key)) {
            updatedRace[key] = existingRace[key];
          }
        }
        // 用新数据覆盖
        for (let key in raceData) {
          if (raceData.hasOwnProperty(key)) {
            updatedRace[key] = raceData[key];
          }
        }
        races[existingIndex] = updatedRace;
      } else {
        // 新增比赛
        if (!raceData._id && !raceData.id) {
          raceData._id = this.generateId();
        } else if (raceData.id && !raceData._id) {
          raceData._id = raceData.id;
        } else if (raceData._id && !raceData.id) {
          raceData.id = raceData._id;
        }
        races.push(raceData);
      }
      
      const filePath = this.getFilePath(this.racesKey);
      return this.writeJsonFile(filePath, races);
    } catch (error) {
      console.error('保存比赛失败:', error);
      return false;
    }
  }

  // 删除比赛
  removeRace(raceId) {
    try {
      const races = this.getAllRaces();
      // 同时支持 id 和 _id 字段
      const filteredRaces = races.filter(race => 
        race._id !== raceId && race.id !== raceId
      );
      
      const filePath = this.getFilePath(this.racesKey);
      const success = this.writeJsonFile(filePath, filteredRaces);
      
      if (success) {
        // 同时删除相关的报名和比赛数据
        this.clearSignups(raceId);
        this.clearMatches(raceId);
      }
      
      return success;
    } catch (error) {
      console.error('删除比赛失败:', error);
      return false;
    }
  }

  // ==================== 报名数据管理 ====================
  
  // 获取比赛的报名数据
  getSignups(raceId) {
    try {
      const filePath = this.getFilePath(this.signupsKey);
      if (!filePath) {
        console.error('无法获取报名文件路径');
        return [];
      }
      const allSignups = this.readJsonFile(filePath) || {};
      return allSignups[raceId] || [];
    } catch (error) {
      console.error('获取报名数据失败:', error);
      return [];
    }
  }

  // 获取所有报名数据
  getAllSignups() {
    try {
      const filePath = this.getFilePath(this.signupsKey);
      if (!filePath) {
        console.error('无法获取报名文件路径');
        return [];
      }
      const allSignups = this.readJsonFile(filePath) || {};
      // 将所有比赛的报名数据合并成一个数组
      const allSignupsArray = [];
      Object.keys(allSignups).forEach(raceId => {
        const raceSignups = allSignups[raceId] || [];
        for (let i = 0; i < raceSignups.length; i++) {
          allSignupsArray.push(raceSignups[i]);
        }
      });
      return allSignupsArray;
    } catch (error) {
      console.error('获取所有报名数据失败:', error);
      return [];
    }
  }

  // 添加报名
  addSignup(raceId, signupData) {
    try {
      const filePath = this.getFilePath(this.signupsKey);
      const allSignups = this.readJsonFile(filePath) || {};
      const raceSignups = allSignups[raceId] || [];
      
      if (!signupData._id) {
        signupData._id = this.generateId();
      }
      
      raceSignups.push(signupData);
      allSignups[raceId] = raceSignups;
      
      return this.writeJsonFile(filePath, allSignups);
    } catch (error) {
      console.error('添加报名失败:', error);
      return false;
    }
  }

  // 更新报名
  updateSignup(raceId, signupData) {
    try {
      const filePath = this.getFilePath(this.signupsKey);
      const allSignups = this.readJsonFile(filePath) || {};
      const raceSignups = allSignups[raceId] || [];
      
      const index = raceSignups.findIndex(signup => signup._id === signupData._id);
      if (index >= 0) {
        raceSignups[index] = signupData;
        allSignups[raceId] = raceSignups;
        return this.writeJsonFile(filePath, allSignups);
      }
      return false;
    } catch (error) {
      console.error('更新报名失败:', error);
      return false;
    }
  }

  // 删除报名
  removeSignup(raceId, signupId) {
    try {
      const filePath = this.getFilePath(this.signupsKey);
      const allSignups = this.readJsonFile(filePath) || {};
      const raceSignups = allSignups[raceId] || [];
      
      const filteredSignups = raceSignups.filter(signup => signup._id !== signupId);
      allSignups[raceId] = filteredSignups;
      
      return this.writeJsonFile(filePath, allSignups);
    } catch (error) {
      console.error('删除报名失败:', error);
      return false;
    }
  }

  // 清空比赛的所有报名
  clearSignups(raceId) {
    try {
      const filePath = this.getFilePath(this.signupsKey);
      const allSignups = this.readJsonFile(filePath) || {};
      delete allSignups[raceId];
      return this.writeJsonFile(filePath, allSignups);
    } catch (error) {
      console.error('清空报名失败:', error);
      return false;
    }
  }

  // 保存比赛的报名列表
  saveSignups(raceId, signupList) {
    try {
      const filePath = this.getFilePath(this.signupsKey);
      const allSignups = this.readJsonFile(filePath) || {};
      allSignups[raceId] = signupList;
      return this.writeJsonFile(filePath, allSignups);
    } catch (error) {
      console.error('保存报名列表失败:', error);
      return false;
    }
  }

  // ==================== 比赛数据管理 ====================
  
  // 获取比赛的所有比赛数据
  getMatches(raceId) {
    try {
      const filePath = this.getFilePath(this.matchesKey);
      const allMatches = this.readJsonFile(filePath) || {};
      return allMatches[raceId] || [];
    } catch (error) {
      console.error('获取比赛数据失败:', error);
      return [];
    }
  }

  // 保存比赛数据
  saveMatches(raceId, matchesData) {
    try {
      const filePath = this.getFilePath(this.matchesKey);
      const allMatches = this.readJsonFile(filePath) || {};
      allMatches[raceId] = matchesData;
      return this.writeJsonFile(filePath, allMatches);
    } catch (error) {
      console.error('保存比赛数据失败:', error);
      return false;
    }
  }

  // 清空比赛的所有比赛数据
  clearMatches(raceId) {
    try {
      const filePath = this.getFilePath(this.matchesKey);
      const allMatches = this.readJsonFile(filePath) || {};
      delete allMatches[raceId];
      return this.writeJsonFile(filePath, allMatches);
    } catch (error) {
      console.error('清空比赛数据失败:', error);
      return false;
    }
  }

  // ==================== 数据导出导入 ====================
  
  // 导出所有数据（用于备份）
  exportAllData() {
    try {
      const races = this.getAllRaces();
      const allSignups = this.readJsonFile(this.getFilePath(this.signupsKey)) || {};
      const allMatches = this.readJsonFile(this.getFilePath(this.matchesKey)) || {};
      
      const exportData = {
        races: races,
        signups: allSignups,
        matches: allMatches,
        exportTime: new Date().toISOString(),
        version: '1.0'
      };
      
      return exportData;
    } catch (error) {
      console.error('导出数据失败:', error);
      return null;
    }
  }

  // 导入所有数据（用于恢复）
  importAllData(data) {
    try {
      if (!data || !data.races) {
        console.error('导入数据格式错误');
        return false;
      }
      
      // 导入比赛数据
      const racesFilePath = this.getFilePath(this.racesKey);
      if (racesFilePath) {
        this.writeJsonFile(racesFilePath, data.races || []);
      }
      
      // 导入报名数据
      const signupsFilePath = this.getFilePath(this.signupsKey);
      if (signupsFilePath) {
        this.writeJsonFile(signupsFilePath, data.signups || {});
      }
      
      // 导入比赛数据
      const matchesFilePath = this.getFilePath(this.matchesKey);
      if (matchesFilePath) {
        this.writeJsonFile(matchesFilePath, data.matches || {});
      }
      
      console.log('数据导入成功');
      return true;
    } catch (error) {
      console.error('导入数据失败:', error);
      return false;
    }
  }

  // 清空所有数据
  clearAllData() {
    try {
      const racesFilePath = this.getFilePath(this.racesKey);
      const signupsFilePath = this.getFilePath(this.signupsKey);
      const matchesFilePath = this.getFilePath(this.matchesKey);
      
      // 删除文件
      try {
        this.fs.unlinkSync(racesFilePath);
      } catch (e) {
        console.log('删除比赛文件失败:', e);
      }
      
      try {
        this.fs.unlinkSync(signupsFilePath);
      } catch (e) {
        console.log('删除报名文件失败:', e);
      }
      
      try {
        this.fs.unlinkSync(matchesFilePath);
      } catch (e) {
        console.log('删除比赛数据文件失败:', e);
      }
      
      return true;
    } catch (error) {
      console.error('清空所有数据失败:', error);
      return false;
    }
  }

  // ==================== 数据统计 ====================
  
  // 获取存储统计信息
  getStorageStats() {
    try {
      const races = this.getAllRaces();
      const filePath = this.getFilePath(this.signupsKey);
      const allSignups = this.readJsonFile(filePath) || {};
      const matchesFilePath = this.getFilePath(this.matchesKey);
      const allMatches = this.readJsonFile(matchesFilePath) || {};
      
      const totalSignups = Object.values(allSignups).reduce((sum, signups) => sum + signups.length, 0);
      const totalMatches = Object.values(allMatches).reduce((sum, matches) => sum + matches.length, 0);
      
      return {
        racesCount: races.length,
        signupsCount: totalSignups,
        matchesCount: totalMatches,
        lastUpdate: new Date().toISOString()
      };
    } catch (error) {
      console.error('获取存储统计失败:', error);
      return null;
    }
  }

  // 获取文件大小（字节）
  getFileSize(filePath) {
    try {
      const stats = this.fs.statSync(filePath);
      return stats.size;
    } catch (error) {
      // 文件不存在或其他错误
      return 0;
    }
  }

  // 获取总存储大小（KB）
  getTotalStorageSize() {
    try {
      const racesFilePath = this.getFilePath(this.racesKey);
      const signupsFilePath = this.getFilePath(this.signupsKey);
      const matchesFilePath = this.getFilePath(this.matchesKey);
      
      const racesSize = this.getFileSize(racesFilePath);
      const signupsSize = this.getFileSize(signupsFilePath);
      const matchesSize = this.getFileSize(matchesFilePath);
      
      const totalSize = racesSize + signupsSize + matchesSize;
      return (totalSize / 1024).toFixed(2); // 转换为KB
    } catch (error) {
      console.error('获取存储大小失败:', error);
      return '0.00';
    }
  }

  // 获取详细存储分析
  getDetailedStorageAnalysis() {
    try {
      const racesFilePath = this.getFilePath(this.racesKey);
      const signupsFilePath = this.getFilePath(this.signupsKey);
      const matchesFilePath = this.getFilePath(this.matchesKey);
      
      const racesSize = this.getFileSize(racesFilePath);
      const signupsSize = this.getFileSize(signupsFilePath);
      const matchesSize = this.getFileSize(matchesFilePath);
      
      // 获取数据内容用于分析
      const races = this.getAllRaces();
      const signups = this.getAllSignups();
      const allMatches = this.readJsonFile(matchesFilePath) || {};
      const totalMatches = Object.values(allMatches).reduce((sum, matches) => sum + matches.length, 0);
      
      return {
        files: {
          races: {
            path: racesFilePath,
            size: racesSize,
            sizeKB: (racesSize / 1024).toFixed(2),
            count: races.length
          },
          signups: {
            path: signupsFilePath,
            size: signupsSize,
            sizeKB: (signupsSize / 1024).toFixed(2),
            count: signups.length
          },
          matches: {
            path: matchesFilePath,
            size: matchesSize,
            sizeKB: (matchesSize / 1024).toFixed(2),
            count: totalMatches
          }
        },
        total: {
          size: racesSize + signupsSize + matchesSize,
          sizeKB: ((racesSize + signupsSize + matchesSize) / 1024).toFixed(2)
        }
      };
    } catch (error) {
      console.error('获取详细存储分析失败:', error);
      return null;
    }
  }
}

// 创建单例实例
const localDataManager = new LocalDataManager();

module.exports = localDataManager; 